package com.iot.manager.ui.fragments;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.button.MaterialButton;
import com.iot.manager.R;
import com.iot.manager.ui.adapters.DeviceDataAdapter;
import com.iot.manager.data.models.DeviceData;
import com.iot.manager.network.ApiService;
import com.iot.manager.network.RetrofitClient;
import com.iot.manager.utils.DateUtils;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class DeviceDataFragment extends Fragment {

    private static final String TAG = "DeviceDataFragment";
    private static final String ARG_DEVICE_ID = "deviceId";
    private static final int PAGE_SIZE = 20;

    private String deviceId;
    private Date startTime;
    private Date endTime;
    private int currentPage = 0;
    private List<DeviceData> allData = new ArrayList<>();
    private List<DeviceData> filteredData = new ArrayList<>();
    private DeviceDataAdapter adapter;
    private RecyclerView recyclerView;
    private ProgressBar progressBar;
    private View errorLayout;
    private TextView errorText;
    private MaterialButton btnRetry;
    private MaterialButton btnPrevPage;
    private MaterialButton btnNextPage;
    private TextView tvPageInfo;
    private EditText etSearch;
    private ApiService apiService;
    private boolean isViewCreated = false;
    private OnDataLoadedListener dataLoadedListener;
    private Date startDate;
    private Date endDate;
    private DeviceDataAdapter deviceDataAdapter;
    private OnDataLoadedListener listener;

    private LinearLayout tableHeaderLayout;
    private LinearLayout paginationLayout;

    public interface OnDataLoadedListener {
        void onDataLoaded(List<DeviceData> data);
    }

    public void setOnDataLoadedListener(OnDataLoadedListener listener) {
        this.listener = listener;
    }

    public static DeviceDataFragment newInstance(String deviceId) {
        DeviceDataFragment fragment = new DeviceDataFragment();
        Bundle args = new Bundle();
        args.putString(ARG_DEVICE_ID, deviceId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_device_data, container, false);
        recyclerView = view.findViewById(R.id.recyclerView);
        progressBar = view.findViewById(R.id.progressBar);
        errorLayout = view.findViewById(R.id.errorLayout);
        errorText = view.findViewById(R.id.errorText);
        btnRetry = view.findViewById(R.id.btnRetry);
        btnPrevPage = view.findViewById(R.id.btnPrevPage);
        btnNextPage = view.findViewById(R.id.btnNextPage);
        tvPageInfo = view.findViewById(R.id.tvPageInfo);
        etSearch = view.findViewById(R.id.etSearch);

        tableHeaderLayout = view.findViewById(R.id.tableHeaderLayout);
        paginationLayout = view.findViewById(R.id.paginationLayout);

        Log.d(TAG, "tableHeaderLayout: " + (tableHeaderLayout != null ? "Found" : "Null"));
        Log.d(TAG, "paginationLayout: " + (paginationLayout != null ? "Found" : "Null"));

        adapter = new DeviceDataAdapter();
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setAdapter(adapter);

        setupListeners(view);

        isViewCreated = true;
        return view;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            deviceId = getArguments().getString(ARG_DEVICE_ID);
        }
        apiService = RetrofitClient.getInstance().getApiService();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        // 初始化日期范围为最近7天
        Calendar calendar = Calendar.getInstance();
        endTime = calendar.getTime();
        calendar.add(Calendar.DAY_OF_MONTH, -7);
        startTime = calendar.getTime();
        loadData();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        isViewCreated = false;
    }

    public void setDateRange(Date startTime, Date endTime) {
        this.startTime = startTime;
        this.endTime = endTime;
        if (isViewCreated) {
            loadData();
        }
    }

    public void setTimeRange(Date startDate, Date endDate) {
        this.startDate = startDate;
        this.endDate = endDate;
        loadHistoryData();
    }

    private void setupListeners(View view) {
        view.findViewById(R.id.btnExport).setOnClickListener(v -> exportAndShareData());
        btnRetry.setOnClickListener(v -> loadData());
        btnPrevPage.setOnClickListener(v -> {
            if (currentPage > 0) {
                currentPage--;
                updatePage();
            }
        });
        btnNextPage.setOnClickListener(v -> {
            int totalPages = (filteredData.size() + PAGE_SIZE - 1) / PAGE_SIZE;
            if (currentPage < totalPages - 1) {
                currentPage++;
                updatePage();
            }
        });

        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}

            @Override
            public void afterTextChanged(Editable s) {
                filterData(s.toString());
            }
        });
    }

    private void loadData() {
        if (!isViewCreated) {
            return;
        }

        if (startTime == null || endTime == null) {
            // 如果没有设置时间范围，加载最近24小时的数据
            endTime = new Date();
            startTime = new Date(endTime.getTime() - 24 * 60 * 60 * 1000);
        }

        showLoading();
        apiService.getDeviceData(deviceId, startTime, endTime).enqueue(new Callback<List<DeviceData>>() {
            @Override
            public void onResponse(Call<List<DeviceData>> call, Response<List<DeviceData>> response) {
                if (!isViewCreated) {
                    return;
                }
                hideLoading();
                if (response.isSuccessful() && response.body() != null) {
                    allData = response.body();
                    filterData(etSearch.getText().toString());
                    showData();
                    if (dataLoadedListener != null) {
                        dataLoadedListener.onDataLoaded(allData);
                    }
                } else {
                    showError("加载数据失败");
                }
            }

            @Override
            public void onFailure(Call<List<DeviceData>> call, Throwable t) {
                if (!isViewCreated) {
                    return;
                }
                hideLoading();
                showError("网络错误：" + t.getMessage());
            }
        });
    }

    private void filterData(String query) {
        filteredData.clear();
        if (query.isEmpty()) {
            filteredData.addAll(allData);
        } else {
            for (DeviceData data : allData) {
                if (data.getTimestamp().toString().contains(query) ||
                    String.valueOf(data.getTemperature()).contains(query) ||
                    String.valueOf(data.getHumidity()).contains(query)) {
                    filteredData.add(data);
                }
            }
        }
        currentPage = 0;
        updatePage();
    }

    private void updatePage() {
        if (!isViewCreated) {
            return;
        }
        int start = currentPage * PAGE_SIZE;
        int end = Math.min(start + PAGE_SIZE, filteredData.size());
        List<DeviceData> pageData = filteredData.subList(start, end);
        adapter.setData(pageData);
        
        int totalPages = (filteredData.size() + PAGE_SIZE - 1) / PAGE_SIZE;
        tvPageInfo.setText(String.format("第 %d/%d 页", currentPage + 1, totalPages));
        btnPrevPage.setEnabled(currentPage > 0);
        btnNextPage.setEnabled(currentPage < totalPages - 1);
    }

    private void showLoading() {
        if (!isViewCreated) {
            return;
        }
        progressBar.setVisibility(View.VISIBLE);
        recyclerView.setVisibility(View.GONE);
        errorLayout.setVisibility(View.GONE);
        tableHeaderLayout.setVisibility(View.GONE);
        paginationLayout.setVisibility(View.GONE);
        Log.d(TAG, "showLoading: tableHeaderLayout GONE, paginationLayout GONE");
    }

    private void showData() {
        if (!isViewCreated) {
            return;
        }
        progressBar.setVisibility(View.GONE);
        recyclerView.setVisibility(View.VISIBLE);
        errorLayout.setVisibility(View.GONE);
        tableHeaderLayout.setVisibility(View.VISIBLE);
        paginationLayout.setVisibility(View.VISIBLE);
        updatePage();
        Log.d(TAG, "showData: tableHeaderLayout VISIBLE, paginationLayout VISIBLE");
    }

    private void showError(String message) {
        if (!isViewCreated) {
            return;
        }
        progressBar.setVisibility(View.GONE);
        recyclerView.setVisibility(View.GONE);
        errorLayout.setVisibility(View.VISIBLE);
        errorText.setText(message);
        tableHeaderLayout.setVisibility(View.GONE);
        paginationLayout.setVisibility(View.GONE);
        Log.d(TAG, "showError: tableHeaderLayout GONE, paginationLayout GONE");
    }

    private void hideLoading() {
        if (!isViewCreated) {
            return;
        }
        progressBar.setVisibility(View.GONE);
    }

    public List<DeviceData> getFilteredData() {
        return filteredData;
    }

    public void updateData(List<DeviceData> data) {
        if (adapter != null) {
            adapter.setData(data);
            adapter.notifyDataSetChanged();
        }
    }

    private void exportAndShareData() {
        if (filteredData.isEmpty()) {
            Toast.makeText(getContext(), "没有数据可导出", Toast.LENGTH_SHORT).show();
            return;
        }

        StringBuilder csv = new StringBuilder();
        csv.append("时间,温度,湿度,状态\n");
        
        for (DeviceData data : filteredData) {
            csv.append(String.format("%s,%.1f,%.1f,%s\n",
                data.getTimestamp(),
                data.getTemperature(),
                data.getHumidity(),
                data.getStatus()));
        }

        try {
            File csvFile = new File(getContext().getExternalCacheDir(), "device_data.csv");
            FileWriter writer = new FileWriter(csvFile);
            writer.append(csv.toString());
            writer.flush();
            writer.close();

            Uri contentUri = FileProvider.getUriForFile(getContext(), getContext().getPackageName() + ".fileprovider", csvFile);

            Intent shareIntent = new Intent(Intent.ACTION_SEND);
            shareIntent.setType("text/csv");
            shareIntent.putExtra(Intent.EXTRA_STREAM, contentUri);
            shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            startActivity(Intent.createChooser(shareIntent, "导出数据"));

        } catch (IOException e) {
            Toast.makeText(getContext(), "导出失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }

    private void loadHistoryData() {
        if (deviceId == null || startDate == null || endDate == null) {
            return;
        }

        String startTime = DateUtils.formatDateTime(startDate);
        String endTime = DateUtils.formatDateTime(endDate);

        RetrofitClient.getInstance().getApiService().getDeviceHistoryData(deviceId, startTime, endTime)
            .enqueue(new Callback<List<DeviceData>>() {
                @Override
                public void onResponse(Call<List<DeviceData>> call, Response<List<DeviceData>> response) {
                    if (getActivity() == null) return;
                    if (response.isSuccessful() && response.body() != null) {
                        getActivity().runOnUiThread(() -> {
                            deviceDataAdapter.updateData(response.body());
                            if (listener != null) {
                                listener.onDataLoaded(response.body());
                            }
                        });
                    } else {
                        getActivity().runOnUiThread(() -> {
                            Toast.makeText(getContext(), "加载历史数据失败", Toast.LENGTH_SHORT).show();
                        });
                    }
                }

                @Override
                public void onFailure(Call<List<DeviceData>> call, Throwable t) {
                    if (getActivity() == null) return;
                    getActivity().runOnUiThread(() -> {
                        Toast.makeText(getContext(), "加载历史数据失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
                    });
                }
            });
    }

    public void setDeviceId(String deviceId) {
        this.deviceId = deviceId;
    }
} 